package com.rongjun.zheng.dao;

import com.rongjun.zheng.model.Course;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Time:2020/9/18
 **/
public class CourseDao {
    public int courseAdd(Connection con, Course course)throws Exception{
        String sql="select * from t_course where courseName=? ";
        PreparedStatement pstmt1=con.prepareStatement(sql);
        pstmt1.setString(1, course.getCourseName());
        ResultSet rs=pstmt1.executeQuery();
        if(rs.next()){
            return 2;
        }
        String sql1="insert into t_course values(null,?,?)";
        PreparedStatement pstmt=con.prepareStatement(sql1);
        pstmt.setString(1, course.getCourseName());
        pstmt.setString(2, course.getCourseRemark());
        return pstmt.executeUpdate();

    }
    public ResultSet courseList(Connection con, Course course)throws Exception{
        StringBuffer sql=new StringBuffer("select * from t_course");
        if(course.getCourseName()!=null){
            sql.append(" and courseName like '%"+course.getCourseName()+"%'");
        }
        PreparedStatement pstmt=con.prepareStatement(sql.toString().replaceFirst("and", "where"));
        return pstmt.executeQuery();
    }
    public int courseDelete(Connection con,String id)throws Exception{
        String sql="delete from t_course where id=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setString(1, id);
        return pstmt.executeUpdate();
    }
    public int courseModify(Connection con,Course course,String id)throws Exception{
        String sql1="select * from t_course where courseName=? and courseRemark=?";
        PreparedStatement pstmt1=con.prepareStatement(sql1);
        pstmt1.setString(1, course.getCourseName());
        pstmt1.setString(2, course.getCourseRemark());
        ResultSet rs=pstmt1.executeQuery();
        if(rs.next()){
            return 2;
        }
        String sql2="select * from t_course where courseName=?";
        PreparedStatement pstmt2=con.prepareStatement(sql2);
        pstmt2.setString(1, course.getCourseName());
        ResultSet rs1=pstmt2.executeQuery();
        if(rs1.next()){
            String sql="update t_course set courseRemark=? where courseName=?";
            PreparedStatement pstmt=con.prepareStatement(sql);
            pstmt.setString(2, course.getCourseName());
            pstmt.setString(1, course.getCourseRemark());
            return pstmt.executeUpdate();
        }
        String sql="update t_course set courseName=?,courseRemark=? where id=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setString(1, course.getCourseName());
        pstmt.setString(2, course.getCourseRemark());
        pstmt.setString(3, id);
        return pstmt.executeUpdate();
    }
}
